package com.yfbao.horizon.docker.trx;


import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.yfbao.horizon.docker.common.UserTrxConstants;
import com.yfbao.horizon.docker.dao.TrxHistoryDao;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 *
 *   //todo:后台定时线程删除历史记录：
 *   1、默认删除60分钟前的事务记录，每隔5分钟执行一次
 *   2、从历史表删除task任务时，需要检查该任务再 task表中不存在，才能删除
 */
@Slf4j
@Component
//@Schedule(jobName = "trxHistory-delete-job", fixedDelay = 10*60*1000, description = "分布式事务历史执行记录删除")
public class TrxHistoryDeleteJob {

    @Autowired
    private TrxHistoryDao trxHistoryDao;
    @Autowired
    private CtpUserDTPServcie ctpUserDTPServcie;

//    @Override
//    public SingleResponse<?> exec() {
//        expiredHistoryDelete();
//        return null;
//    }

    //执行删了历史记录
    @Scheduled( fixedDelay = 5*60*1000)
    public void expiredHistoryDelete(){
        log.info("begin do expiredHistoryDelete Job...");
        DateTime dateTime = DateUtil.offsetMinute(new Date(), (-1) * UserTrxConstants.TASK_HISTORY_LIVE_TIME);
//        Wrapper wrapper = new Wrapper(TrxHistory.class);
//        wrapper.and().andLessThan("updateTime",dateTime);
//        List<TrxHistory> trxHistories = trxHistoryDao.selectListByWrapperIgnoreTenant(wrapper);
//        if(trxHistories == null || trxHistories.isEmpty()){
//            log.info("delete over time trxHistory task empty");
//            return;
//        }
//        List<Long> batchDelTrxIds =new ArrayList<>();
//        int deleteNum= 0;
//        for (TrxHistory trxHistory : trxHistories) {
//            if(batchDelTrxIds.size()>100){
//                ctpUserDTPServcie.batchDeleteHistory(batchDelTrxIds);
//                deleteNum = deleteNum+batchDelTrxIds.size();
//                batchDelTrxIds.clear();
//            }
//            Long trxId = trxHistory.getTrxId();
//            if( StringUtils.isBlank(trxHistory.getType()) || trxHistory.getType().equals(UserTrxConstants.CHECK)){
//                batchDelTrxIds.add(trxId);
//                continue;
//            }
//            if(trxHistory.getType().equals(UserTrxConstants.COMMIT) && trxHistory.getTaskRes()){
//                batchDelTrxIds.add(trxId);
//                continue;
//            }
////            Apps.getRequestContext().setTenantId(trxHistory.getTenantId());
//            boolean checkTrxTaskExist = ctpUserDTPServcie.checkTrxTaskExist(trxId);
//            if(!checkTrxTaskExist){
//                batchDelTrxIds.add(trxId);
//            }
//        }
//        if(!batchDelTrxIds.isEmpty()){
//            ctpUserDTPServcie.batchDeleteHistory(batchDelTrxIds);
//            deleteNum = deleteNum+batchDelTrxIds.size();
//        }
//        log.info("delete over time trxHistory task,num:"+deleteNum);
    }



}
